<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="6" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"/>
        </div>
        <div class="head-container dept-tree">
          <el-tree
            v-loading="treeLoading"
            :props="defaultProps"
            :data="treeDeptData"
            node-key="id"
            :expand-on-click-node="false"
            :default-expanded-keys="treeExpandData"
            :filter-node-method="filterNode"
            highlight-current
            ref="tree"
            @node-click="handleNodeClick"/>
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="18" :xs="24" class="user-table">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="用户工号" prop="loginName">
            <el-input
              v-model="queryParams.loginName"
              placeholder="请输入用户工号"
              clearable
              size="small"
              style="width: 200px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="用户名称" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入用户名称"
              clearable
              size="small"
              style="width: 200px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="用户状态"
              clearable
              size="small"
              style="width: 200px">
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <right-toolbar :showSearch.sync="showSearch" @queryTable="initUserList"></right-toolbar>
        </el-row>

        <el-table v-loading="table.loading" :data="table.data">
          <!--<el-table-column type="selection" width="50" align="center"/>-->
          <el-table-column label="用户工号" align="center" key="loginName" prop="loginName"/>
          <el-table-column label="用户名称" align="center" key="userName" prop="userName" :show-overflow-tooltip="true"/>
          <el-table-column label="性别" align="center" key="sexName" prop="sexName"/>
          <el-table-column label="所属组织" align="center" key="orgName" prop="orgName" :show-overflow-tooltip="true"/>
          <el-table-column label="所属部门" align="center" key="deptName" prop="deptName" :show-overflow-tooltip="true"/>
          <el-table-column label="岗位" align="center" key="postName" prop="postName" width="120"/>
          <el-table-column label="状态" align="center" key="status">
            <template slot-scope="scope">
              <status-tag :status-options="statusOptions" :status="scope.row.status"></status-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <div>
                <el-link
                  type="primary"
                  icon="el-icon-edit"
                  :underline="false"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:user:edit']">
                  分配角色
                </el-link>
                <el-link
                  type="success"
                  icon="el-icon-connection"
                  :underline="false"
                  @click="handleSetPartTime(scope.row)"
                  v-hasPermi="['system:user:partTime']">
                  兼职
                </el-link>
              </div>
              <div>
                <el-link
                  type="danger"
                  icon="el-icon-key"
                  :underline="false"
                  @click="handleResetPwd(scope.row)"
                  v-hasPermi="['system:user:resetPwd']">
                  重置密码
                </el-link>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="page.total > 0"
          :total="page.total"
          :page.sync="page.current"
          :limit.sync="page.size"
          @pagination="initUserList"/>
      </el-col>
    </el-row>

    <edit-user-role ref="userRole" @success="handleQuery"></edit-user-role>
    <tree-selector ref="orgSelector" title="选择组织" :init-fn="initDeptList" :multiple-mode="true" @set-value="setOrg"></tree-selector>
  </div>
</template>

<script>
import { listUser, resetUserPwd, userJzList, saveUserJz } from "@/api/system/user";
import { deptTree } from "@/api/system/dept";

import EditUserRole from "./components/editUserRole";
import TreeSelector from "@/components/TreeSelector";
import JzBtn from "./components/jzBtn";

export default {
  name: "User",
  components: {
    EditUserRole,
    TreeSelector,
    JzBtn
  },
  data() {
    return {
      showSearch: true,
      // 部门名称
      deptName: undefined,
      treeLoading: false,
      treeDeptData: [],
      treeExpandData:[],
      statusOptions: [],
      defaultProps: {
        children: "children",
        label: "name",
        isLeaf: 'leaf'
      },
      // 查询参数
      queryParams: {
        loginName: undefined,
        userName: undefined,
        status: undefined,
        orgId: undefined,
        deptId: undefined
      },
      table: {
        data: [],
        loading: false,
      },
      page: {
        total: 0,
        current: 1,
        size: 10,
      },
      initDeptList: {
        fn: deptTree
      },
      selectedUser: undefined
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      this.initDeptTree();
      this.initUserList();
      this.getDicts("sys_normal_disable").then(res => {
        this.statusOptions = res;
      })
    },
    initDeptTree() {
      this.treeLoading = true;
      deptTree().then(res => {
        this.treeLoading = false;

        this.treeDeptData = res;
        this.$lodash.forEach(res, item => {
          this.treeExpandData.push(item.id);
        });
      }).catch(() => {
        this.treeLoading = false;
      });
    },
    /** 查询用户列表 */
    initUserList() {
      this.table.loading = true;
      listUser({
        loginName: this.queryParams.loginName,
        userName: this.queryParams.userName,
        status: this.queryParams.status,
        orgId: this.queryParams.orgId,
        deptId: this.queryParams.deptId,
        page: true,
        current: this.page.current,
        size: this.page.size,
      }).then(response => {
        this.table.data = response.records;
        this.page.total = response.total;
        this.table.loading = false;
      }).catch(() => {
        this.table.loading = false;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) {
        return true;
      }
      return data.name.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      if (data.bzflag === "Z") {
        this.queryParams.orgId = data.id;
        this.queryParams.deptId = undefined;
      } else {
        this.queryParams.orgId = undefined;
        this.queryParams.deptId = data.id;
      }
      this.initUserList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.page.current = 1;
      this.initUserList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$refs.userRole.init(row.id);
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$confirm('是否重置"' + row.userName + '"的密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      }).then(function() {
        return resetUserPwd(row.id);
      }).then(() => {
        this.msgSuccess("重置成功");
      }).catch(() => {});
    },
    handleSetPartTime(row) {
      this.selectedUser = row.loginName;
      userJzList({
        userCode: this.selectedUser
      }).then(res => {
        const selections = [];
        this.$lodash.forEach(res, item => {
          selections.push({
            id: item.orgId,
            name: item.orgName,
            orgName: item.orgName
          })
        });
        this.$refs.orgSelector.init(selections);
      }).catch(() => {
        this.$refs.orgSelector.init([]);
      });
    },
    setOrg(selections) {
      this.saveJz(selections, "Z");
    },
    saveJz(selections, orgType) {
      if (selections && selections.length > 0) {
        const orgIds = [];
        this.$lodash.forEach(selections, item => {
          orgIds.push(item.id);
        });
        saveUserJz({
          userCode: this.selectedUser,
          orgIds: orgIds,
          orgType: orgType
        }).then(res => {
          this.msgSuccess("设置成功");
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
  .dept-tree {
    height: 76vh;
    overflow: auto;
    & ::v-deep .el-tree {
      display: inline-block;
    }

    & ::v-deep .el-tree__empty-text {
      display: contents;
    }
  }
</style>
